var express = require('express');
var IntakeSchema = require('../../../modules/intake');
var router = express.Router();

//列表显示 搜索查询
  router.get('/list', function (req, res, next) {
    let cond = {};
    req.query.campus ? cond.campus = { $regex: req.query.campus} : '';

    IntakeSchema.find(cond,{}).exec((err, doc)=>{
      if (!err && doc) {
        res.json({
          code: 200,
          data: doc,
        });
        return res.end();
      } else {
        res.status(500);
        res.json({code: 10000, msg: '数据库异常，查询失败'});
        return res.end();
      }
    })
  });
  //删除
  router.post('/del', function (req, res, next) {
    if (!req.body.id) {
      res.json({code: 500, msg: '缺少参数id'});
      return res.end();
    }
    IntakeSchema.findOne({_id: req.body.id}).exec((err, doc)=>{
      if (!err && doc) {
        IntakeSchema.remove({_id: doc._id}, (err) => {
          if (!err) {
            res.json({code: 200, msg: '成功去除该年级！'});
            return res.json();
          } else {
            res.status(500);
            res.json({code: 10000, msg: '数据库异常，删除失败'});
            return res.end();
          }
        });
      } else {
        res.status(500);
        res.json({code: 10000, msg: '数据库异常，查询失败'});
        return res.end();
      }
    });
  });
  //新增
  router.post('/add', function(req, res, next) {
    let label = req.body.label;
    new Promise((resolve, reject)=>{
      var query  = IntakeSchema.where({'label' : label});
      query.findOne(function (err, doc){
        if (!err && !doc) {
          resolve();
        }else {
          reject(err);
        }
      });
    }).then(()=>{
      let insertData = new IntakeSchema({
        'campus': req.body.campus ? req.body.campus : '',
        'label': req.body.label ? req.body.label : '',
        'value': req.body.value ? req.body.value : '',
      }, false);
      insertData.save(function (err) {
        if (err) {
          res.json({code: 401, msg: '新增失败，请重试！'});
          return res.end();
        } else {
          res.json({code: 200, msg: '新增成功！' });
          return res.end();
        }
      });
    }).catch(()=>{
      res.json({code: 500, msg: '该年级信息已存在！'});
      return res.end();
    });
  });
  //编辑
  router.post('/upd', function(req, res, next){
    let data = req.body
    IntakeSchema.findByIdAndUpdate({ _id: data._id }, {$set: {
      'campus': req.body.campus ? req.body.campus : '',
      'label': req.body.label ? req.body.label : '',
      'value': req.body.value ? req.body.value : '',
    }}, function (err, raw) {
      if (!err) {
        res.json({code: 200, msg: '更新成功'});
        return res.end();
      } else {
        res.json({code: 500, msg: '更新失败'});
        return res.end();
      }
    }); 
  });

  module.exports = router;
  